var cropped = false;
var cropOnSave = false;
var imageWidth = 0;
var imageHeight = 0;

var newStyles = [];
var delStyles = [];

var newScripts = [];
var delScripts = [];

$(function(){

	$('.pageText').markItUp(mySettings);
	$('.pageText_tiny').tinymce(TinyMCESettings);
	
	$(".inputType").change(function() {
		if ($(this).val() == 'markitup')
		{
			$('#pageTextDiv_markitup').show();
			$('#pageTextDiv_tinymce').hide();
		}
		else
		{
			$('#pageTextDiv_markitup').hide();
			$('#pageTextDiv_tinymce').show();
		}
	});
	
	$("#nameInput").bind('input propertychange', function () {
		$("#addressInput").val(translit.convert($(this).val()));
	});
	
	$("#saveButton").click(function() {
		$.post(base_url+'admin/articles/checkShortUrl', {url: $("#addressInput").val(), id:pageId}, function(data) {
			if (data == '1')
			{
				alert("Этот короткий адрес уже используется");
				return false;
			} else {
				$("#cropOnSave").val(cropOnSave?1:0);
				$("#newAddStyles").val(JSON.stringify(newStyles));
				$("#delAddStyles").val(JSON.stringify(delStyles));
				$("#newAddScripts").val(JSON.stringify(newScripts));
				$("#delAddScripts").val(JSON.stringify(delScripts));
				$("#blogForm").submit();
			}
		});
	});

	var button = $("#uploadButton"), interval;
	var uploadButtonHtml = '';
	$.ajax_upload(button, {
		action : base_url+"admin/articles/loadPhoto/",
		name : 'file',
		
		onSubmit : function(file, ext) 
		{
			uploadButtonHtml = $("#uploadButton").html();
			$("#uploadButton").html("<img src='" + base_url + "img/loading.gif' />");
			this.disable();
		},
		
		onComplete : function(file, response) 
		{
			$("#uploadButton").html(uploadButtonHtml);
			switch (response)
			{
				case '0': response = 'Мухлёж!'; break;
				case '1': response = 'Ошибка загрузки файла'; break;
				case '2': response = 'Попытка загрузить не изображение'; break;
				default:
					$("#poImgInput").val(response);
					response = '<img src="'+response+'" width="200"/>';
			}
			$('#uploadImgDiv').css({"width": "200px","height":"auto","overflow":"visible"});
			$("#uploadImgDiv").html(response);
			cropped = false;
			cropOnSave = true;
			this.enable();
		}
	});

	$("#cropImage").click(function()
	{
		$("#cropDiv").show();

		if (!cropped)
		{
			$("#cropDivManageImg").html('<img src="'+$("#poImgInput").val()+'"/>');
			$("#uploadImgDiv").html('<img width="200" src="'+$("#poImgInput").val()+'"/>');
			$("#cropDivManageImgPreview").attr('src', $("#poImgInput").val()).css({
					'height': 'auto',
					'margin-left': '0',
					'margin-top': '0',
					'width': 'auto'
				});
			
			imageWidth = $("#cropDivManageImgPreview").width();
			imageHeight = $("#cropDivManageImgPreview").height();

			$('#cropDivManageImg img').Jcrop({
				onSelect: showCoords,
				onChange: showCoords,
				bgOpacity: .3,
				aspectRatio: 1
			});
			
			cropped = true;
		}
	});

	$("#cropDiv").click(function(e){
		if (e.target.id == 'cropDiv')
		{
			$("#cropDiv").hide();
			//$("#cropMetrix input").val('');
			//cropped = false;
		}
	})

	$("#cropMetrixButton").click(function(){
		$("#cropDiv").hide();
		return false;
	})
	
	$("#restoreImage").click(function(){
		
		$('#uploadImgDiv').css({"width": "200px","height":"auto","overflow":"visible"});
		$('#uploadImgDiv img').attr('src', $("#poImgInput").val());
		
		cropOnSave = true;
		return false;
	});

	$("#tBlog").change(function()
	{
		var page = $(this).val();
		$.each($("#tCategory option"), function(key, val)
		{
			if($(val).attr('data-page') == page)
				$(val).removeAttr('disabled').attr('selected', false);
			else
				$(val).attr('disabled', 'disabled').attr('selected', false);
		})

		$('#tCategory').multipleSelect('refresh').multipleSelect("uncheckAll");
	});

	var page = $("#tBlog").val();
	$.each($("#tCategory option"), function(key, val)
	{
		if ($(val).attr('data-page') != 0 && $(val).attr('data-page') != page) {
			$(val).attr('disabled', 'disabled');
		}
	})

	$('#tCategory').multipleSelect({
		selectAllText: 'Все категории',
		width: '185px',
		maxHeight: '500px',
		name: '_categories[]'
	});
})

function showCoords(c)
{
	$("input[name='c[x]']").val(c.x);
	$("input[name='c[y]']").val(c.y);
	$("input[name='c[x2]']").val(c.x2);
	$("input[name='c[y2]']").val(c.y2);
	$("input[name='c[w]']").val(c.w);
	$("input[name='c[h]']").val(c.h);
	
	var rx = 200 / c.w;
	var ry = 200 / c.h;
	
	$('#cropDivManageImgPreview').css({
		width: Math.round(rx * imageWidth) + 'px',
		height: Math.round(ry * imageHeight) + 'px',
		marginLeft: '-' + Math.round(rx * c.x) + 'px',
		marginTop: '-' + Math.round(ry * c.y) + 'px'
	});
	
	$('#uploadImgDiv').css({
		"width": "200px",
		"height":"200px",
		"overflow":"hidden"
	});

	$('#uploadImgDiv img').css({
		width: Math.round(rx * imageWidth) + 'px',
		height: Math.round(ry * imageHeight) + 'px',
		marginLeft: '-' + Math.round(rx * c.x) + 'px',
		marginTop: '-' + Math.round(ry * c.y) + 'px'
	});

	cropOnSave = true;
};

function addStyle()
{
	var newStyle = $("#newStyle").val();
	if (newStyle.length > 1)
	{
		newStyles.push(newStyle);
		$("#addStylesListDiv").append($("<div/>").addClass("oneStyle").text(newStyle).append('<img src="' + base_url + 'img/admin/remove.png" height="14" onClick="delStyle(this)" class="removeImg"/>'));
		$("#newStyle").val('');
	}
}

function addScript()
{
	var newScript = $("#newScript").val();
	if (newScript.length > 1)
	{
		newScripts.push(newScript);
		$("#addScriptsListDiv").append($("<div/>").addClass("oneScript").text(newScript).append('<img src="' + base_url + 'img/admin/remove.png" height="14" onClick="delScript(this)" class="removeImg"/>'));
		$("#newScript").val('');
	}
}

function delStyle(e)
{
	var divo = $(e).closest('.oneStyle');
	if (typeof divo.attr("data-id") == "undefined")
		delete newStyles[newStyles.indexOf($(divo).text())];
		else
		delStyles.push(divo.attr("data-id"));
	divo.remove();
}

function delScript(e)
{
	var divo = $(e).closest('.oneScript');
	if (typeof divo.attr("data-id") == "undefined")
		delete newScripts[newScripts.indexOf($(divo).text())];
		else
		delScripts.push(divo.attr("data-id"));
	divo.remove();
}